//routers/aima.js

const GROUP_NAME = 'aima';
const models = require('../models');
const Joi = require('joi');
const Op = require('sequelize').Op;
const {jwtHeaderDefine} = require('../utils/router-helper');
const {
  paginationDefine
} = require('../utils/router-helper');
// const sd = require('silly-datetime');

const getTimeTange = (dateType) => {//day: 今天； week: 近一周； month：近一月；
    let now = new Date();
    let [year,month,day,date,nowtimes] = [now.getFullYear(),now.getMonth()+1,now.getDay(),now.getDate(),now.getTime()];
    let lastWeekNow = new Date(new Date().getTime()-(date - 1) * 24 * 60 * 60 * 1000);
    let tomorrow = new Date(`${year}-${month}-${date} 00:00:00`).getTime();
    let [weekYear,weekMonth,weekDate] = [lastWeekNow.getFullYear(),lastWeekNow.getMonth()+1,lastWeekNow.getDate()];
    let lastWeek = new Date(`${weekYear}-${weekMonth}-${weekDate} 00:00:00`).getTime();
    let lastMonthNow = new Date(new Date().getTime()-(date - 1) * 24 * 60 * 60 * 1000);
    let [monthYear,monthMonth,monthDate] = [lastMonthNow.getFullYear(),lastMonthNow.getMonth()+1,lastMonthNow.getDate()];
    let lastMonth = new Date(`${monthYear}-${monthMonth}-${monthDate} 00:00:00`).getTime();
    if(dateType === 'day') {
        return [tomorrow,now.getTime()];
    };
    if(dateType === 'week') {
        return [lastWeek,now.getTime()];
    };
    if(dateType === 'month') {
        return [lastMonth,now.getTime()];
    };
}

module.exports = [{
    method: 'POST',
    path: `/${GROUP_NAME}/addSale`,
    handler: async (request,reply) => {
        let info = request.payload.saleInfo;
        await models.electric_sale.create({
            purchaseTime: info.purchaseTime,
            customerId: info.customerId,
            brandId: info.brandId,
            price: info.price,
            remark: info.remark,
            operateId: info.operateId,
            billImageUrl: info.billImageUrl,
            paymentId: info.paymentId,
            paymentBank: info.paymentBank,
            isExchange: info.isExchange,
            exchangeGoods: info.exchangeGoods,
            isDivide: info.isDivide,
            dividePeriods: info.dividePeriods,
            nowDividePeriods: info.nowDividePeriods,
            divideStartDatetime: info.divideStartDatetime,
            divideEndDatetime: info.divideEndDatetime,
            dividePrice: info.dividePrice,
            statusId: info.statusId
        })
        .then((res) => {
            reply({
                code: '0',
                msg: 'success',
                result: res
            })
        })
        .catch((err) => {
            reply({
                code: '-1',
                msg: 'error',
                result: err.errors
            })
        })
    },
    config: {
        tags: ['api', `${GROUP_NAME}`],
        description: '添加销售记录',
        validate: {
          payload: {
            saleInfo: Joi.object().keys({
                purchaseTime: Joi.string().required(),
                customerId: Joi.number().integer().required(),
                brandId: Joi.number().integer().required(),
                price: Joi.number().required(),
                remark: Joi.string().allow(""),
                operateId: Joi.number().integer().required(),
                billImageUrl: Joi.string().allow(""),
                paymentId: Joi.number().integer().required(),
                paymentBank: Joi.string().allow(""),
                isExchange: Joi.number().allow(0),
                exchangeGoods: Joi.string().allow(""),
                isDivide: Joi.number().allow(0),
                dividePeriods: Joi.number().allow(0),
                nowDividePeriods: Joi.number().allow(0),
                divideStartDateTime: Joi.string().allow(""),
                divideEndDateTime: Joi.string().allow(""),
                dividePrice: Joi.number().allow(0),
                statusId: Joi.number().integer().required()
            }),
          },
          ...jwtHeaderDefine,
        },
        cors: {//设置允许跨域   调试web端使用
          origin: ['*'],
          additionalHeaders: ['cache-control', 'x-requested-with']
        }
    }
},{
    method: 'POST',
    path: `/${GROUP_NAME}/addOperator`,
    handler: async (request,reply) => {
        let info = request.payload;
        await models.operators.create({
            operatorName: info.operatorName
        })
        .then((res) => {
            reply({
                code: '0',
                msg: 'success',
                result: res
            })
        })
        .catch((err) => {
            reply({
                code: '-1',
                msg: 'error',
                result: err.errors
            })
        })
    },
    config: {
        tags: ['api',`${GROUP_NAME}`],
        description: '添加工作人员',
        validate: {
            payload: {
                operatorName: Joi.string().required()
            },
            ...jwtHeaderDefine,
        },
        cors: {//设置允许跨域   调试web端使用
          origin: ['*'],
          additionalHeaders: ['cache-control', 'x-requested-with']
        }
    }
},{
    method: 'POST',
    path: `/${GROUP_NAME}/addCustomer`,
    handler: async (request,reply) => {
        let info = request.payload.customerInfo;
        await models.customers.create({
            customerName: info.customerName,
            phone: !!info.phone ? info.phone : "",
            address: !!info.address ? info.address : "",
            idcardNo: info.idcardNo
        })
        .then((res) => {
            reply({
                code: '0',
                msg: 'success',
                result: res
            })
        })
        .catch((err) => {
            if(err && err.errors && err.errors[0] && err.errors[0].type === 'unique violation') {
                reply({
                    code: '-2',
                    msg: 'error',
                    result: err.errors
                })
            }else {
                reply({
                    code: '-1',
                    msg: 'error',
                    result: err.errors
                })
            }
        })
    },
    config: {
        tags: ['api',`${GROUP_NAME}`],
        description: '添加顾客信息',
        validate: {
            payload: {
                customerInfo: Joi.object().keys({
                    customerName: Joi.string().required(),
                    phone: Joi.string().allow(""),
                    address: Joi.string().allow(""),
                    idcardNo: Joi.string().required()
                })
            },
            ...jwtHeaderDefine,
        },
        cors: {//设置允许跨域   调试web端使用
          origin: ['*'],
          additionalHeaders: ['cache-control', 'x-requested-with']
        }
    }
},{
    method: 'POST',
    path: `/${GROUP_NAME}/addRepair`,
    handler: async (request,reply) => {
        let info = request.payload.repairInfo;
        await models.repair_service.create({
            operateTime: info.operateTime,
            detailAffairs: info.detailAffairs,
            paymentId: info.paymentId,
            isDoorToDoor: info.isDoorToDoor,
            operatorId: info.operatorId,
            repairId: info.repairId,
            price: info.price
        })
        .then((res) => {
            reply({
                code: '0',
                msg: 'success',
                result: res
            })
        })
        .catch((err) => {
            reply({
                code: '-1',
                msg: 'error',
                result: err.errors
            })
        })
    },
    config: {
        tags: ['api',`${GROUP_NAME}`],
        description: '添加维修记录',
        validate: {
            payload: {
                repairInfo: Joi.object().keys({
                    operateTime: Joi.string().required(),
                    detailAffairs: Joi.string().allow(""),
                    price: Joi.number().required(),
                    paymentId: Joi.number().required(),
                    isDoorToDoor: Joi.number().allow(0),
                    operatorId: Joi.number().required(),
                    repairId: Joi.number().required()
                })
            },
            ...jwtHeaderDefine,
        },
        cors: {//设置允许跨域   调试web端使用
          origin: ['*'],
          additionalHeaders: ['cache-control', 'x-requested-with']
        }
    }
},{
    method: 'POST',
    path: `/${GROUP_NAME}/queryCustomers`,
    handler: async (request,reply) => {
        let info = request.payload;
        let param = {};
        !!info.id ? Object.assign(param,{
            id: info.id
        }) : null;
        !!info.idcardNo ? Object.assign(param,{
            idcardNo: info.idcardNo
        }) : null;
        let params = {
            // 基于 id 的条件查询
            where: param,
            attributes: [
              'id',
              'customerName',
              'phone',
              'address',
              'idcardNo'
            ]
        }
        if(request.payload.pagination) {
            Object.assign(params,{
                limit: request.payload.limit,
                offset: (request.payload.page - 1) * request.payload.limit,
            })
        }
        const {
            rows: results,
            count: totalCount
        } = await models.customers.findAndCountAll(params);
          // 开启分页的插件，返回的数据结构里，需要带上 result 与 totalCount 两个字段
        reply({
            code: '0',
            msg: 'ok',
            results,
            totalCount
        });
    },
    config: {
        tags: ['api',`${GROUP_NAME}`],
        description: '查询用户',
        validate: {
            ...jwtHeaderDefine,
            payload: {
                id: Joi.number().allow(0),
                idcardNo: Joi.string().allow(''),
                ...paginationDefine
            }
        },
        cors: {//设置允许跨域   调试web端使用
          origin: ['*'],
          additionalHeaders: ['cache-control', 'x-requested-with']
        }
    }
},{
    method: 'POST',
    path: `/${GROUP_NAME}/queryOperators`,
    handler: async (request,reply) => {
        let info = request.payload;
        let queryParams = {
            attributes: [
                'id',
                'operatorName',
                'userId'
            ]
        };
        if(!!info.id) {
            Object.assign(queryParams,{
                where: {
                    id: info.id
                }
            })
        }
        const {
            rows: results,
            count: totalCount
        } = await models.operators.findAndCountAll(queryParams);
          // 开启分页的插件，返回的数据结构里，需要带上 result 与 totalCount 两个字段
        reply({
            code: '0',
            msg: 'ok',
            results,
            totalCount
        });
    },
    config: {
        tags: ['api',`${GROUP_NAME}`],
        description: '查询员工',
        validate: {
            payload: {
                id: Joi.number()
            },
            query: {
                ...paginationDefine
            },
            ...jwtHeaderDefine,
        },
        cors: {//设置允许跨域   调试web端使用
          origin: ['*'],
          additionalHeaders: ['cache-control', 'x-requested-with']
        }
    }
},{
    method: 'POST',
    path: `/${GROUP_NAME}/queryBrands`,
    handler: async (request,reply) => {
        let info = request.payload;
        let queryParams = {
            attributes: [
                'id',
                'brandName'
            ]
        };
        if(!!info.id) {
            Object.assign(queryParams,{
                where: {
                    id: info.id
                }
            })
        }
        const {
            rows: results,
            count: totalCount
        } = await models.brands.findAndCountAll(queryParams);
          // 开启分页的插件，返回的数据结构里，需要带上 result 与 totalCount 两个字段
        reply({
            code: '0',
            msg: 'ok',
            results,
            totalCount
        });
    },
    config: {
        tags: ['api',`${GROUP_NAME}`],
        description: '查询品牌',
        validate: {
            payload: {
                id: Joi.number()
            },
            ...jwtHeaderDefine,
        },
        cors: {//设置允许跨域   调试web端使用
          origin: ['*'],
          additionalHeaders: ['cache-control', 'x-requested-with']
        }
    }
},{
    method: 'POST',
    path: `/${GROUP_NAME}/queryPayment`,
    handler: async (request,reply) => {
        let info = request.payload;
        let queryParams = {
            attributes: [
                'id',
                'paymentName'
            ]
        };
        if(!!info.id) {
            Object.assign(queryParams,{
                where: {
                    id: info.id
                }
            })
        }
        const {
            rows: results,
            count: totalCount
        } = await models.payment.findAndCountAll(queryParams);
          // 开启分页的插件，返回的数据结构里，需要带上 result 与 totalCount 两个字段
        reply({
            code: '0',
            msg: 'ok',
            results,
            totalCount
        });
    },
    config: {
        tags: ['api',`${GROUP_NAME}`],
        description: '查询支付方式',
        validate: {
            payload: {
                id: Joi.number()
            },
            ...jwtHeaderDefine,
        },
        cors: {//设置允许跨域   调试web端使用
          origin: ['*'],
          additionalHeaders: ['cache-control', 'x-requested-with']
        }
    }
},{
    method: 'POST',
    path: `/${GROUP_NAME}/queryRepairType`,
    handler: async (request,reply) => {
        let info = request.payload;
        let queryParams = {
            attributes: [
                'id',
                'repairName'
            ]
        };
        if(!!info.id) {
            Object.assign(queryParams,{
                where: {
                    id: info.id
                }
            })
        }
        const {
            rows: results,
            count: totalCount
        } = await models.repair_type.findAndCountAll(queryParams);
          // 开启分页的插件，返回的数据结构里，需要带上 result 与 totalCount 两个字段
        reply({
            code: '0',
            msg: 'ok',
            results,
            totalCount
        });
    },
    config: {
        tags: ['api',`${GROUP_NAME}`],
        description: '查询维修种类',
        validate: {
            payload: {
                id: Joi.number()
            },
            ...jwtHeaderDefine,
        },
        cors: {//设置允许跨域   调试web端使用
          origin: ['*'],
          additionalHeaders: ['cache-control', 'x-requested-with']
        }
    }
},{
    method: 'POST',
    path: `/${GROUP_NAME}/queryStatus`,
    handler: async (request,reply) => {
        let info = request.payload;
        let queryParams = {
            attributes: [
                'id',
                'statusName'
            ]
        };
        if(!!info.id) {
            Object.assign(queryParams,{
                where: {
                    id: info.id
                }
            })
        }
        const {
            rows: results,
            count: totalCount
        } = await models.status.findAndCountAll(queryParams);
          // 开启分页的插件，返回的数据结构里，需要带上 result 与 totalCount 两个字段
        reply({
            code: '0',
            msg: 'ok',
            results,
            totalCount
        });
    },
    config: {
        tags: ['api',`${GROUP_NAME}`],
        description: '查询销售状态',
        validate: {
            payload: {
                id: Joi.number()
            },
            ...jwtHeaderDefine,
        },
        cors: {//设置允许跨域   调试web端使用
          origin: ['*'],
          additionalHeaders: ['cache-control', 'x-requested-with']
        }
    }
},{
    method: "POST",
    path: `/${GROUP_NAME}/querySaleList`,
    handler: async (request,reply) => {
        let info = request.payload;
        let queryParams = {};
        if(!!info.dateType) {
            Object.assign(queryParams,{
                where: {
                    purchaseTime: {
                        [Op.between]: getTimeTange(info.dateType)
                    }
                }
            })
        }
        if(!!info.startDate && !!info.endDate && !info.dateType) {
            Object.assign(queryParams,{
                where: {
                    purchaseTime: {
                        [Op.between]: [info.startDate.getTime(),info.endDate.getTime()]
                    }
                }
            })
        }
        if(!!info.customerId) {
            Object.assign(queryParams,{
                where: {
                    customerId: info.customerId
                }
            })
        }
        if(!!info.brandId) {
            Object.assign(queryParams,{
                where: {
                    brandId: info.brandId
                }
            })
        }
        if(!!info.operateId) {
            Object.assign(queryParams,{
                where: {
                    operateId: info.operateId
                }
            })
        }
        if(!!info.paymentId) {
            Object.assign(queryParams,{
                where: {
                    paymentId: info.paymentId
                }
            })
        }
        if(!!info.statusId) {
            Object.assign(queryParams,{
                where: {
                    statusId: info.statusId
                }
            })
        }
        if(!!info.isDivide) {
            Object.assign(queryParams,{
                where: {
                    isDivide: info.isDivide
                }
            })
        }
        if(!!info.isExchange) {
            Object.assign(queryParams,{
                where: {
                    isExchange: info.isExchange
                }
            })
        }
        Object.assign(queryParams,{
            limit: info.limit,
            offset: (info.page - 1) * info.limit,
            include: [{
                model: models.customers
            },{
                model: models.brands
            },{
                model: models.operators,
                attributes: [
                    'id',
                    'operatorName',
                    'userId'
                ]
            },{
                model: models.payment
            },{
                model: models.status,
            }]
        })
        const {rows: results, count: totalCount} = await models.electric_sale.findAndCountAll(queryParams);
        // 开启分页的插件，返回的数据结构里，需要带上 result 与 totalCount 两个字段
        reply({
            code: '0',
            msg: 'ok',
            results,
            totalCount
        });
    },
    config: {
        tags: ['api',`${GROUP_NAME}`],
        description: '查询销售列表',
        validate: {
            ...jwtHeaderDefine,
            payload: {
                dateType: Joi.string(), //day: 今天； week: 近一周； month：近一月；
                startDate: Joi.date().timestamp('javascript'),
                endDate: Joi.date().timestamp('javascript'),
                customerId: Joi.number(),
                brandId: Joi.number(),
                operateId: Joi.number(),
                paymentId: Joi.number(),
                statusId: Joi.number(),
                isDivide: Joi.number(),//1 true; 0 false
                isExchange: Joi.number(),//1 true; 0 false
                ...paginationDefine
            }
        },
        cors: {//设置允许跨域   调试web端使用
          origin: ['*'],
          additionalHeaders: ['cache-control', 'x-requested-with']
        }
    }
},{
    method: 'POST',
    path: `/${GROUP_NAME}/queryRepairList`,
    handler: async (request,reply) => {
        let info = request.payload;
        let queryParams = {};
        if(!!info) {
            if(!!info.dateType) {
                Object.assign(queryParams,{
                    where: {
                        operateTime: {
                            [Op.between]: getTimeTange(info.dateType)
                        }
                    }
                })
            }
            if(!!info.startDate && !!info.endDate && !info.dateType) {
                Object.assign(queryParams,{
                    where: {
                        operateTime: {
                            [Op.between]: [info.startDate.getTime(),info.endDate.getTime()]
                        }
                    }
                })
            }
            if(!!info.paymentId) {
                Object.assign(queryParams,{
                    where: {
                        paymentId: info.paymentId
                    }
                })
            }
            if(!!info.operatorId) {
                Object.assign(queryParams,{
                    where: {
                        operatorId: info.operatorId
                    }
                })
            }
            if(!!info.repairId) {
                Object.assign(queryParams,{
                    where: {
                        repairId: info.repairId
                    }
                })
            }
            if(!!info.isDoorToDoor) {
                Object.assign(queryParams,{
                    where: {
                        isDoorToDoor: info.isDoorToDoor
                    }
                })
            }
        }
        Object.assign(queryParams,{
            limit: info.limit,
            offset: (info.page - 1) * info.limit,
            include: [{
                model: models.operators,
                attributes: [
                    'id',
                    'operatorName',
                    'userId'
                ]
            },{
                model: models.payment
            },{
                model: models.repair_type
            }]
        })
        const {
            rows: results,
            count: totalCount
        } = await models.repair_service.findAndCountAll(queryParams);
          // 开启分页的插件，返回的数据结构里，需要带上 result 与 totalCount 两个字段
        reply({
            code: '0',
            msg: 'ok',
            results,
            totalCount
        });
    },
    config: {
        tags: ['api',`${GROUP_NAME}`],
        description: '查询维修列表',
        validate: {
            ...jwtHeaderDefine,
            payload: {
                dateType: Joi.string(), //day: 今天； week: 近一周； month：近一月；
                startDate: Joi.date().timestamp('javascript'),
                endDate: Joi.date().timestamp('javascript'),
                paymentId: Joi.number(),
                operatorId: Joi.number(),
                repairId: Joi.number(),
                isDoorToDoor: Joi.number(),//1 true; 0 false
                ...paginationDefine
            },
        },
        cors: {//设置允许跨域   调试web端使用
          origin: ['*'],
          additionalHeaders: ['cache-control', 'x-requested-with']
        }
    }
}]
